package com.RuiJi.controller;

import com.RuiJi.entity.User;
import com.RuiJi.service.UserService;
import com.RuiJi.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Twinkle
 * @PACKAGE_NAME: com.RuiJi.controller
 * @NAME: UserController
 * @USER: Twinkle
 * @DATE: 2023/4/14
 * @TIME: 22:36
 * @YEAR: 2023
 * @MONTH: 04
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private JavaMailSender javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;


    @PostMapping("/sendEmail")
    public R<String> sendSimpleMail(@RequestBody User user, HttpSession session) {
        String email = user.getEmail();
        System.out.println("=========" + email);
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送者
        message.setFrom(from);
        // 设置邮件接收者
        message.setTo(email);
        // 设置邮件的主题
        message.setSubject("登录验证码");
        // 设置邮件的正文
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code.append(r);
        }
        String text ="您的验证码为：" + code + ",请勿泄露给他人。时效五分钟嗷";
        System.out.println(code);
        message.setText(text);
        //将验证码缓存到redis中
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
        session.setAttribute("email",email);
        //session.setAttribute("code",code);
        Object email1 = session.getAttribute("email");
        Object code1 = session.getAttribute("code");
        //Object sessionAttribute = session.getAttribute(String.valueOf(code));
        //System.out.println(code1 + "---------------" + email1);
        // 发送邮件
        try {
            javaMailSender.send(message);
            return R.success("发送成功");
        } catch (MailException e) {
            e.printStackTrace();
        }

        return R.success("发送失败");
    }


    /**
     * 登录方法
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取邮箱
        String email = map.get("email").toString();
        //System.out.println("===================");
        //System.out.println(code+"==============================="+email);
        //获取验证码
        //Object codeInSession = session.getAttribute("code");
        //从redis中获取缓存验证码
        Object codeInSession = redisTemplate.opsForValue().get(email);
        Object email1 = session.getAttribute("email");
        //System.out.println(codeInSession + "========" + email1);
        //从Sesson内获取保存的验证码。
        if (codeInSession != null && codeInSession.equals(codeInSession)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail, email);

            User user = userService.getOne(queryWrapper);
            if (user == null) {
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setEmail(email);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());

            //登录成功删除缓存验证码
            redisTemplate.delete(email);
            return R.success(user);
        }
        return R.error("登录失败");
    }


    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("email");
        return R.success("退出成功");


    }
}
